package com.example.maryttsspringbootdemo.service;

import marytts.LocalMaryInterface;
import marytts.MaryInterface;
import marytts.exceptions.SynthesisException;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.sound.sampled.AudioInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Service
public class MaryTtsService {

    private MaryInterface mary;


    @PostConstruct
    public void init() throws Exception {
        mary = new LocalMaryInterface();
        // 设置voice-cmu-slt-hsmm音源
        mary.setVoice("cmu-slt-hsmm");
        mary.setOutputType("AUDIO");
        mary.setAudioEffects("WAVE");
    }

    /**
     * 将文本转换为音频字节流（WAV 格式）
     */
    public byte[] textToSpeech(String text) throws IOException, SynthesisException {
        AudioInputStream buffered = mary.generateAudio(text);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = buffered.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        return baos.toByteArray();
    }
}